移动设备和桌面电脑上的客户端api起初并不是同步的。最初总是移动设备上先拥有某些功能和相应的api,但慢慢的,这些api会出现在桌面电脑上。其中一个应用接口技术就是getusermedia api,它能让应用开发者访问用户的摄像头或内置相机。

如何通过浏览器来访问你的摄像头,并提取截屏图形:

html<video id="video" width="640" height="480" autoplay></video>
<button id="snap">snap photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
javascript// put event listeners into place
window.addeventlistener("domcontentloaded", function() {
    // grab elements, create settings, etc.
    var canvas = document.getelementbyid("canvas"),
    context = canvas.getcontext("2d"),
    video = document.getelementbyid("video"),
    videoobj = { "video": true },
    errback = function(error) {
        console.log("video capture error: ", error.code);
    };
    // put video listeners into place
    if(navigator.getusermedia) { // standard
            navigator.getusermedia(videoobj, function(stream) {
            video.src = stream;
            video.play();
        }, errback);
    } else if(navigator.webkitgetusermedia) { // webkit-prefixed
            navigator.webkitgetusermedia(videoobj, function(stream){
            video.src = window.webkiturl.createobjecturl(stream);
            video.play();
        }, errback);
    }
    else if(navigator.mozgetusermedia) { // firefox-prefixed
            navigator.mozgetusermedia(videoobj, function(stream){
            video.src = window.url.createobjecturl(stream);
            video.play();
        }, errback);
    }
}, false);

拍照的功能,在按钮上加入一个监听器,将视频画面画到画布上。

javascript// 触发拍照动作
document.getelementbyid("snap")
    .addeventlistener("click", function() {
    context.drawimage(video, 0, 0, 640, 480);
});

dada86
993 声望22 粉丝

多努力一点点。